// @ts-ignore
import {dockerLogin} from '../src/login';
import * as sinon from 'sinon';
import {expect} from 'chai'
import * as step from '@flow-step/step-toolkit';
import process from "process";
import { IParams } from '../src/params';

describe('Docker Setup Function', () => {
    let sandbox: sinon.SinonSandbox;
    let stepInfoStub: sinon.SinonStub;
    let execCallStub: sinon.SinonStub;
    let exportEnvVarStub: sinon.SinonStub;
    let processEnv: NodeJS.ProcessEnv;
    let getDockerAcrPersonalCertificateStub: sinon.SinonStub;

    beforeEach(() => {
        sandbox = sinon.createSandbox();
        stepInfoStub = sandbox.stub(step, 'info');
        execCallStub = sandbox.stub(step.exec, 'call').resolves(0);
        exportEnvVarStub = sandbox.stub(step, 'exportEnvVar');
        getDockerAcrPersonalCertificateStub = sandbox.stub(step.certificate, 'getDockerAcrPersonalCertificate');
        getDockerAcrPersonalCertificateStub.resolves({username: 'mockUser', password: 'mockPass'});
        processEnv = process.env;
    });

    afterEach(() => {
        sandbox.restore();
        process.env = processEnv;
    });

    it('should handle "serviceConnection" authType correctly', async () => {
        process.env.NODEGROUP_TYPE = "K8S"
        process.env.SERVICE_CONNECTION_ID = 'mockServiceConnectionId';
        process.env.FLOW_JOB_TOKEN = 'mockFlowJobToken';

        let params = new IParams()
        params.region = 'cn-beijing'
        params.dockerRepository = 'crpi-xxxxx.cn-beijing.personal.cr.aliyuncs.com/ns/repo'
        params.useVpcAddress = true

        await dockerLogin(params);

        sinon.assert.calledWith(getDockerAcrPersonalCertificateStub, 'mockFlowJobToken', 'mockServiceConnectionId')
        sinon.assert.calledWith(execCallStub, 'docker', ['login', '-u', 'mockUser', '-p', 'mockPass', 'crpi-xxxxx-vpc.cn-beijing.personal.cr.aliyuncs.com'])
    });

    it('should throw error when docker login fails', async () => {
        execCallStub.resolves(1);
        try {
            let params = new IParams()
            params.region = 'cn-beijing'
            params.dockerRepository = 'crpi-xxxxx.cn-hangzhou.personal.cr.aliyuncs.com'
            params.useVpcAddress = false
            await dockerLogin(params);
            expect.fail('Expected an error to be thrown');
        } catch (error) {
            // @ts-ignore
            expect(error.message).to.include('docker login -u');
            // @ts-ignore
            expect(error.message).to.include('but error');
        }
    });
});
